package com.myshiro.controller;

import com.myshiro.pojo.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController {

   @RequestMapping({"/","login"})
    public String login(){
       return "login";
   }
    @RequestMapping({"logout"})
    public String logout(){
        return "login";
    }
    @RequestMapping({"doLogin","doLogin.html"})
    public String doLogin(@RequestParam String username
                        , @RequestParam String password
                          , Model model){

       //调用service.login方法,验证用户名是否正确

        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username,password);

            Subject subject = SecurityUtils.getSubject();
            subject.login(token); // --> 账密给了shiro

            //调用后台方法实现登录逻辑的验证
            //认证|登录-->shiro

            SysUser currUser = (SysUser) subject.getPrincipal(); // 从shiro再次拿回 principal

            return "redirect:main";  //没有抛异常,就是代表认证成功
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute("msg","账密错误,登录失败");
        }catch (LockedAccountException  e) {
            model.addAttribute("msg",e.getMessage());//被锁定
        }catch (AuthenticationException e) {
            model.addAttribute("msg","认证异常,登录失败");
        }

        return "login";
    }
    @RequestMapping({"main"})
    public String main(){
        return "index";
    }

    @RequestMapping({"/unauthorizedUrl"})
    public String unauthorizedUrl(){
        return "403";
    }

}
